
package SfxUrlIndex;

use strict;
use URI; 

use constant DEFAULT_INSTITUTE => "DEFAULT";

sub new {
	my $proto = shift;
	my $class = ref($proto) || $proto;
	my $self  = {};
	
	$self->{'INDEX_HASH'}   = {};

	bless ($self, $class);
	return $self;
}

sub indexHash {
	my $self = shift;
	
	return $self->{'INDEX_HASH'};
}


sub addToIndex {
	my $self = shift;
	my $sfxUrlObj = shift;
	
	my $hashRef = $self->indexHash();
	my $canonicalDomain = $sfxUrlObj->canonicalDomain();
	
	push @{$hashRef->{$canonicalDomain}}, $sfxUrlObj;
	
	
	return $sfxUrlObj;
}

	
sub makeEzproxyConfig {
	my $self = shift;
	my $outputHandleRef = shift;

	my $hash = $self->indexHash();
	foreach my $domain ( keys %$hash ) {
		my $arrayRef = $hash->{$domain};
	
	

		my $firstSfxUrl = $arrayRef->[0];
		my %hostsSeen;
		#This will of course just be the title for the first
		#URL encountered at this baseurl/domain. Oh well, title
		#isn't really used for much anyway.
		print $outputHandleRef "Title " . $firstSfxUrl->targetName();
		print $outputHandleRef ": " . $firstSfxUrl->displayName();
		if ($#$arrayRef > 0 ) { print $outputHandleRef " (and others)"; }
		print $outputHandleRef "\n";
		print $outputHandleRef "URL " . $firstSfxUrl->url() . "\n";
		$hostsSeen{$firstSfxUrl->host()} =1;
		print $outputHandleRef "Domain " . $domain . "\n";
		$hostsSeen{$domain} = 1;
		# Add one with guessed host 'www' too.
		my $wwwGuessedHost = 'www.'.$domain;
		if ( $wwwGuessedHost ne $firstSfxUrl->host() ) {
			#According to EZProxy docs, this should be 'Host', but we decided
			#to make it duplicate "URL" instead, not sure why. 
			#print $outputHandleRef "Host ".$wwwGuessedHost."\n";
			print $outputHandleRef 'URL http://'.$wwwGuessedHost."\n";
			$hostsSeen{$wwwGuessedHost } = 1;
		}
		#Okay, we have to put some 'host' lines in maybe.
		# Keep our hostsSeen hash to avoid adding the same host twice.  

		for ( my $i = 1; $i <= $#$arrayRef ; $i++) {
			my $extraHost = $arrayRef->[$i]->host();
			if ( ! exists $hostsSeen{ $extraHost } ) {
				#EZProxy docs suggest this should be 'Host', but we do
				#'URL' instead, not sure why. 
				#print $outputHandleRef "Host $extraHost\n";
				print $outputHandleRef 'URL http://' .$extraHost."\n";
				$hostsSeen{ $extraHost } = 1;
			}			
		}
		print $outputHandleRef "\n";
	}
}


return 1;

